package com.example.ktapplication.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.R
import com.example.ktapplication.bean.CollectBeanDataX
import com.example.ktapplication.databinding.HomeRecyclerviewItemLayoutBinding

class CollectAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    private val links by lazy {
        mutableListOf<CollectBeanDataX>()
    }

    var itemCallBack: OnItemClickListener? = null

    @SuppressLint("NotifyDataSetChanged")
    fun addData(data: List<CollectBeanDataX>, loadMore:Boolean) {
        if (loadMore){
            links.addAll(data)
        }else{
            links.clear()
            links.addAll(data)
        }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.home_recyclerview_item_layout, parent, false)
        return CollectViewHolder(view)
    }


    override fun getItemCount(): Int {
        return links.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is CollectViewHolder) {
            val bean: CollectBeanDataX = links.get(position)
            holder.binding.imgCollect.visibility=View.INVISIBLE
            holder.binding.txtAuthor.text=
                "作者:" + (if (bean.author.isEmpty()) "未知" else bean.author)

            holder.binding.txtTitle.text = bean.title
            holder.binding.txtTime.text = "时间:" + (bean.niceDate)
            holder.binding.tvtLable.text = "来源:" + bean.chapterName
            holder.binding.llBody.setOnClickListener { view: View? ->
                ///跳转WEB
                if (itemCallBack != null) {
                    itemCallBack!!.onItemClick(bean)
                }
            }
        }
    }

    inner class CollectViewHolder(item: View) : RecyclerView.ViewHolder(item) {
        val binding by lazy {
            HomeRecyclerviewItemLayoutBinding.bind(item)
        }
    }

    interface OnItemClickListener {
        fun onItemClick(bean: CollectBeanDataX)
    }
}